<template>
    <div class="app-container">
        <el-card>
            <el-form ref="form" :model="user" :rules="rules" label-width="80px" class="form">
                <el-form-item label="旧密码" prop="oldPwd">
                    <el-input v-model="user.oldPwd" placeholder="请输入旧密码" type="password" show-password />
                </el-form-item>
                <el-form-item label="新密码" prop="newPwd">
                    <el-input v-model="user.newPwd" placeholder="请输入新密码" type="password" show-password />
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPwd">
                    <el-input v-model="user.confirmPwd" placeholder="请确认密码" type="password" show-password />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" size="mini" @click="submit">保存</el-button>
                    <el-button type="danger" size="mini" @click="resetForm">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script>
import { updateUserPwd } from '@/api/system/user'
export default {
    name: 'ResetPW',
    components: {},
    data() {
        const equalToPassword = (rule, value, callback) => {
            if (this.user.newPwd !== value) {
                callback(new Error('两次输入的密码不一致'))
            } else {
                callback()
            }
        }
        return {
            user: {
                oldPwd: undefined,
                newPwd: undefined,
                confirmPwd: undefined
            },
            // 表单校验
            rules: {
                oldPwd: [{ required: true, message: '旧密码不能为空', trigger: 'blur' }],
                newPwd: [
                    { required: true, message: '新密码不能为空', trigger: 'blur' },
                    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
                ],
                confirmPwd: [
                    { required: true, message: '确认密码不能为空', trigger: 'blur' },
                    { required: true, validator: equalToPassword, trigger: 'blur' }
                ]
            }
        }
    },
    created() {},
    methods: {
        submit() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    updateUserPwd(this.user).then((res) => {
                        this.$message.success(res.msg)
                        let isDev = process.env.NODE_ENV === 'development'
                        this.$store.dispatch('LogOut').then(() => {
                            location.href = isDev ? '/' : '/devDist/'
                        })
                    })
                }
            })
        },
        resetForm() {
            this.$refs['form'].resetFields()
        }
    }
}
</script>
<style scoped lang="scss">
.form {
    width: 400px;
    margin: 100px auto;
}
</style>
